package com.idanchuang.support.etcache.remote.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.idanchuang.support.etcache.exception.InvalidRemoteKeyException;
import com.idanchuang.support.etcache.remote.RemoteKey;
import org.springframework.lang.NonNull;

import java.nio.charset.StandardCharsets;

/**
 * RemoteKeyCodec 的 fastjson 实现
 *
 * @author yjy
 * Created at 2021/12/21 9:51 下午
 */
public class FastjsonRemoteKeyCodec implements RemoteKeyCodec {

    private final static byte FIRST_TOKEN_BYTE = '{';
    private final static byte SECOND_TOKEN_BYTE = '"';

    @NonNull
    @Override
    public byte[] encode(@NonNull RemoteKey k) {
        String jsonString = JSON.toJSONString(k);
        return jsonString.getBytes(StandardCharsets.UTF_8);
    }

    @NonNull
    @Override
    public RemoteKey decode(@NonNull byte[] bytes) {
        if (bytes.length < 2 || bytes[0] != FIRST_TOKEN_BYTE || bytes[1] != SECOND_TOKEN_BYTE) {
            throw new InvalidRemoteKeyException(bytes);
        }
        try {
            String jsonString = new String(bytes, StandardCharsets.UTF_8);
            RemoteKey remoteKey = JSON.parseObject(jsonString, RemoteKey.class);
            if (remoteKey.getCn() == null || remoteKey.getKbs() == null) {
                throw new InvalidRemoteKeyException(bytes);
            }
            return remoteKey;
        } catch (JSONException e) {
            throw new InvalidRemoteKeyException(bytes);
        }
    }

}
